import ipConfig from '@/utils/ipConfig.js'

const errorCode = {
  '000': '操作太频繁，请勿重复请求',
  '401': '用户凭证已过期',
  '403': '当前操作没有权限',
  '404': '资源不存在',
  '417': '未绑定登录账号，请使用密码登录后绑定',
  '423': '演示环境不能操作，如需了解联系冷冷',
  '426': '用户名不存在或密码错误',
  '428': '验证码错误,请重新输入',
  '429': '请求过频繁',
  '479': '演示环境，没有权限操作',
  'default': '系统未知错误,请反馈给管理员'
}

export default({ url, params, method='GET', header={}, options={}, loading=false })=> {
	let token = uni.getStorageSync('token')	//token
	// console.log(token);
	if (token) {
	  header['Authorization'] = 'Bearer ' + token;
	  // header['Access-Control-Allow-Origin'] = "*";//跨域
	}
	if(loading) uni.showLoading({ title: '加载中...', mask: true});	//开启loading
	uni.getNetworkType({
			success: function (res) {
					if(res.networkType == '2g' || res.networkType == '3g' || res.networkType == 'none'){
						uni.showToast({
							title:'当前网络质量不佳',
							icon: 'none'
						})
					}
			}
	});
	return new Promise((resolve, reject) => {
		uni.request({
			url: ipConfig.ip + url,
			data: params,
			method: method,
			header: {
				'Accept-Language':'zh-CN,zh;q=0.9',
				// 'Content-Type': 'application/json;charset=UTF-8',
				...header 
			},
			...options,
			success: (res)=> {
				resolve(res.data);
				uni.hideLoading(); //关闭loading
			},
			fail: (res)=> {
				reject(res);
				uni.hideLoading(); //关闭loading
			},
			complete: (res)=>{
				uni.hideLoading(); //关闭loading
				if(res.statusCode == 401){
					uni.removeStorage({
						key: 'token',
						complete: ()=>{
							setTimeout(() => {
								uni.reLaunch({
									url:'/pages/Login/Login'
								})
							},2000)
						}
					});
				}
				if(res.statusCode == 200){
					if(res.data.code&&res.data.code != 20000){
						uni.showToast({
							title: res.data.message,
							icon: 'none',
							duration: 3000
						})
					}
				}else{
					let message = errorCode[res.statusCode] || errorCode['default'];
					uni.showToast({
						title: message,
						icon: 'none',
						duration: 3000
					})
				}
			}
		})
	})
}